package com.zxq.memory;

import java.util.concurrent.*;

public class ByteArrayPools {


    static Integer coreSize = 2;
    static Integer maxSize = 20;
    static Long keepAlive = 5L;
    static Integer queueSize = 10000;
   // static Integer alive_time = 30000;


    /**
     * hash容器
     */
    static ConcurrentHashMap<String, ConcurrentLinkedQueue<byte[]>> hashLinkMap = new ConcurrentHashMap<>();

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize,maxSize,keepAlive,TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(queueSize));


    /**
     * 根据长度，获取对应的byte[]数组
     * @param len
     * @return
     */
    public static byte[] getBytes(String len) {
        ConcurrentLinkedQueue<byte[]> queue = null;
        if(hashLinkMap.get(len) == null) {
            queue = new ConcurrentLinkedQueue();
            hashLinkMap.put(len,queue);
        }
        queue = hashLinkMap.get(len);
        byte[] buff =  queue.poll();
        if(buff == null) {
            buff = new byte[Integer.parseInt(len)];
        }
//        byte[] finalBuff = buff;
//        executor.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(alive_time);
//                    recycle(finalBuff);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
        return buff;
    }


    /**
     * 回收对应的byte[]数组
     * @param array
     */
     static void recycle(byte[] array) {
        String len = array.length + "";
        for(int i =0; i < array.length; i++) {
            array[i] = 0x00;
        }
        ConcurrentLinkedQueue<byte[]> queue =  hashLinkMap.get(len);
        queue.offer(array);
    }




}
